<?php

namespace app\admin\controller\shops;

use app\common\controller\Backend;
use app\common\model\UserMoneyLog;
use app\common\service\BusinessService;
use think\Db;
use think\Exception;
use think\Loader;
use app\common\model\UserShareImage;
use wechat\Wechat;
use app\admin\model\Play;
use app\common\model\OrderProof;

/**
 * 商家管理
 *
 */
class Middleman extends Backend
{

    /**
     * 模型对象
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $this->view->assign("statusList", $this->model->getStatusList());
        // $this->db2 = Db::connect(config('database.db2'));
        $this->assignconfig("middleman", ['id' => config('play.middleman_id')]);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = 'user.user_type=3';
            if (isset($decode['nickname']) && $decode['nickname']) {
                $where2 .= ' and user.nickname like "%'.$decode['nickname'].'%"';
            }
            if (isset($decode['anickname']) && $decode['anickname']) {
                $where2 .= ' and admin.nickname like "%'.$decode['anickname'].'%"';
            }
            if (isset($decode['mobile']) && $decode['mobile']) {
                $where2 .= ' and user.mobile like "%'.$decode['mobile'].'%"';
            }
            if (isset($decode['no']) && $decode['no']) {
                $where2 .= ' and middleman.no like "%'.$decode['no'].'%"';
            }
            if (isset($decode['real_name']) && $decode['real_name']) {
                $where2 .= ' and middleman.real_name like "%'.$decode['real_name'].'%"';
            }
            if (isset($decode['card_no']) && $decode['card_no']) {
                $where2 .= ' and middleman.card_no like "%'.$decode['card_no'].'%"';
            }
            if (isset($decode['bank_name']) && $decode['bank_name']) {
                $where2 .= ' and middleman.bank_name like "%'.$decode['bank_name'].'%"';
            }
            if (isset($decode['ledger_no']) && $decode['ledger_no']) {
                $where2 .= ' and middleman.ledger_no="'.$decode['ledger_no'].'"';
            }
            if (isset($decode['status']) && $decode['status']) {
                $where2 .= ' and user.status="'.$decode['status'].'"';
            }
            $auth_group_access = Db::name('auth_group_access')->alias('aga')->where(['aga.uid'=>$this->auth->id])->find();
            $groups = [];
            if ($auth_group_access['group_id']==3) { // 业务员
                $groups[] = $this->auth->id;
            } elseif ($auth_group_access['group_id']==5) { // 经理
                $groups[] = $this->auth->id;
                $admin = Db::name('admin')->where(['leader'=>$this->auth->id])->find();
                foreach ($admin as $key => $value) {
                    $groups[] = $value['id'];
                }
            }
            if ($groups) {
                $where2 .= ' and middleman.salesman_admin_id in ('.implode(',', $groups).')';
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = Db::name('user')
                ->alias('user')
                ->field('user.id,user.avatar,middleman.no,user.nickname,user.mobile,user.money,user.freeze_money,user.logintime,user.status,middleman.real_name,middleman.card_no,middleman.bank_name,middleman.rebate_amt,admin.nickname as anickname,middleman.ledger_no')
                ->join('chbc_middleman middleman','middleman.user_id=user.id','left')
                ->join('chbc_admin admin','middleman.salesman_admin_id=admin.id','left')
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);
            $list2 = $list->items();

            foreach ($list2 as &$row) {
                $row['bill'] = '';
                if (config('play.middleman_id')==$row['id']) {
                    $row['bill'] = Db::name('play_order')->where('order_status in (3,6,-9) and play_order_no=0 and is_pay=0')->value('sum(rebate_amt)');
                }
            }
            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function wallet($ids)
    {
        // $middleman = Db::name('middleman')->where('no',$ids)->find();
        // $ids = $middleman['user_id'];
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $fields = ['money' => 'money', 'bond' => 'bond_money'];
            $field = input('field', '');
            $value = input('val', 0);
            if (!in_array($field, array_keys($fields))) $this->error('不能修改');
            if ($value == 0) $this->error('变动不能为0');
            Db::startTrans();
            try {
                if ($field == 'money') {
                    $afterMoney = bcadd($row->money, $value,2);
                    $extend = [
                        'before_money' => $row->money,
                        'after_money' => $afterMoney,
                        'log_status' => 1,
                        'operation_name' => $this->auth->nickname,
                    ];
                    UserMoneyLog::addLog($row->id, 11, $value, '管理员操作', $extend);
                    //变更余额
                    $row->money = $afterMoney;
                    $row->save();
                    Db::commit();
                    $this->success('操作成功', null, $afterMoney);
                } elseif ($field == 'bond') {
                    $afterBond = bcadd($row->bond_money, $value,2);
                    $res = (new BusinessService())->bondMoneyLog($row, 1, $value, '管理员操作');
                    if ($res) {
                        Db::commit();
                        $this->success('操作成功', null, $afterBond);
                    }
                }
                Db::rollback();
                $this->error('操作失败', null);
            } catch (Exception $e) {
                Db::rollback();
                $this->error('操作失败', null);
            }
//            $this->success("Ajax请求成功", null, ['id' => $ids]);
//            $this->success("Ajax请求成功", null, 542);
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $middleman = Db::name('middleman')->where(['user_id'=>$row['id'],'no'=>['>',0]])->find();
                if (!$middleman) {
                    $this->error('数据有误');
                }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $update['phone'] = $params['mobile'];
                    $update['real_name'] = $params['real_name'];
                    $update['card_no'] = $params['card_no'];
                    $update['bank_name'] = $params['bank_name'];
                    $update['rebate_amt'] = $params['rebate_amt'];
                    $update['salesman_admin_id'] = $params['salesman_admin_id'];
                    $update['ledger_no'] = $params['ledger_no'];
                    $update['update_dt'] = date("Y-m-d H:i:s");
                    Db::name('middleman')->where(['user_id'=>$row['id'],'no'=>['>',0]])->update($update);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $middleman = Db::name('middleman')->where(['user_id'=>$row['id'],'no'=>['>',0]])->find();
        $this->view->assign("middle", $middleman);
        $salesmanList = $this->salesmanList();
        $this->view->assign("salesmanList", $salesmanList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lh($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['status'] == 'hidden') {
            $this->error(__('请不要重复拉黑！'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                $reason = input('reason', '','htmlentities');
                // 审核通过
                $result = $row->allowField(true)->save([
                    'status' => 'hidden',
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$ids,
                    'status'=>1,
                    'submit_by'=>$this->auth->id,
                    'mode'=>1,
                    'type'=>'管理员拉黑',
                    'reason'=>$reason
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }  

    public function hfjy($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($row['status'] == 'normal') {
            $this->error(__('状态有误'));
        }
        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                // 审核通过
                $result = $row->allowField(true)->save([
                    'status' => 'normal',
                    'updatetime' => time(),
                ]);
                Db::name('blacklist_item')->insert([
                    'user_id'=>$ids,
                    'status'=>1,
                    'submit_by'=>$this->auth->id,
                    'mode'=>3
                ]);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function item()
    {
        $ids = input('ids',0);
        if (!$ids) $this->error('缺少参数');
        $middleman = Db::name('middleman')->where(['user_id'=>$ids])->find();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $shop_no = input('ids','');// 店铺编号
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $shop_nos = Db::name('shop')->where(['middleman_id'=>$middleman['id']])->field('shop_no')->select();
            if (!$shop_nos) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $shop_no = '';
            foreach ($shop_nos as $key => $value) {
                $shop_no .= $value['shop_no'].',';
            }
            $shop_no = trim($shop_no,',');
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = '1=1';
            if (isset($decode['id']) && $decode['id']) {
                $where2 .= ' and a.id = "'.$decode['id'].'"';
            }
            if (isset($decode['place_time']) && $decode['place_time']) {
                $date = explode(' - ', $decode['place_time']);
                $where2 .= ' and a.place_time >"'.strtotime($date[0]).'" and a.place_time<"'.strtotime($date[1]).'"';
            }
            if (isset($decode['is_pay'])) {
                $where2 .= ' and a.is_pay ='.$decode['is_pay'];
            }
            // 云瞻活动经纪人
            // $yunzhanuser = 37161;
            $yunzhanuser = config('play.middleman_id');
            if ($ids==$yunzhanuser) {
                $sql2 = 'select count(*) as count from (select o.* from chbc_play_order o where o.order_status in (3,6,-9) and o.play_order_no=0) a where '.$where2;
                $total = Db::query($sql2);
                $sql = 'select a.* from (select o.* from chbc_play_order o where o.order_status in (3,6,-9) and o.play_order_no=0) a where '.$where2.' order by a.id desc limit '.$offset.','.$limit;
                $list = Db::query($sql);
                foreach ($list as $k => &$v) {
                    $OrderProof2 = new \app\common\model\OrderProof2();
                    $content = json_decode($v['proposal'],1);
                    if (!$content) $content=[];
                    list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($v['play_no'],$v['crood_type'],$content);
                    $proof = $OrderProof2->where('play_order_no',$v['yunzhan_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,actual_pay')->find();
                    if ($v['cps_id']>0) {
                        $v['one_image'] = '';
                    } else {
                        $v['one_image'] = config('oss_domain').$proof['one_image'];
                    }
                    $v['two_image'] = config('oss_domain').$proof['two_image'];
                    $v['three_image'] = config('oss_domain').$proof['three_image'];
                    $v['wm_order_sn'] = $proof['wm_order_sn'];
                    $v['actual_pay'] = $proof['actual_pay'];
                    $v['back_money_text2'] = $play['back_money_text2'];
                    $v['scheme_no_text'] = $play['scheme_no_text'];
                    $v['rebate_amt'] = $v['actual_rebate_amt']+$v['service_charge_amt'];
                    $v['user_id'] = Db::name('user')->where('id',$v['user_id'])->value('nickname');
                    $v['shop_no'] = $shop['shop_name'];
                    $v['platform_no'] = config('platform')[$shop['shop_type']];
                    $v['play_order_no'] = $v['yunzhan_order_no'];
                }
            } else {
                $sql2 = 'select count(*) as count from (select o.* from chbc_play_order o left join chbc_user_money_log uml on o.play_order_no=uml.tran_no where o.order_status in (3,6,-9) and uml.user_id='.$ids.' and uml.log_type=12 union select o.* from chbc_play_order o left join chbc_shop s on s.shop_no=o.shop_no where o.shop_no in ('.$shop_no.') and o.order_status in (3,6,-9) and o.is_pay=0) a where '.$where2;
                $total = Db::query($sql2);
                $sql = 'select a.* from (select o.* from chbc_play_order o left join chbc_user_money_log uml on o.play_order_no=uml.tran_no where o.order_status in (3,6,-9) and uml.user_id='.$ids.' and uml.log_type=12 union select o.* from chbc_play_order o left join chbc_shop s on s.shop_no=o.shop_no where o.shop_no in ('.$shop_no.') and o.order_status in (3,6,-9) and o.is_pay=0) a where '.$where2.' order by a.id desc limit '.$offset.','.$limit;
                $list = Db::query($sql);
                foreach ($list as $k => &$v) {
                    $Play2 = new \app\admin\model\Play2();
                    $OrderProof2 = new \app\common\model\OrderProof2();
                    $play = $Play2->where('play_no',$v['play_no'])->field('*')->find();
                    $proof = $OrderProof2->where('play_order_no',$v['play_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,actual_pay')->find();
                    if ($v['cps_id']>0) {
                        $v['one_image'] = '';
                    } else {
                        $v['one_image'] = config('oss_domain').$proof['one_image'];
                    }
                    $v['two_image'] = config('oss_domain').$proof['two_image'];
                    $v['three_image'] = config('oss_domain').$proof['three_image'];
                    $v['wm_order_sn'] = $proof['wm_order_sn'];
                    $v['actual_pay'] = $proof['actual_pay'];
                    $v['back_money_text2'] = $play['back_money_text2'];
                    $v['scheme_no_text'] = $play['scheme_no_text'];
                    $v['rebate_amt'] = $v['actual_rebate_amt']+$v['service_charge_amt'];
                    $v['user_id'] = Db::name('user')->where('id',$v['user_id'])->value('nickname');
                    $shop = Db::name('shop')->where('shop_no',$v['shop_no'])->find();
                    $v['shop_no'] = $shop['shop_name'];
                    $v['platform_no'] = config('platform')[$shop['shop_type']];
                }
            }

            $result = array("total" => $total[0]['count'], "rows" => $list);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new \app\common\model\Order();
        $list = $model->alias('order')->where('order.shop_no="'.$row['shop_no'].'" and order.order_status=3')->order('order.id asc')->field('order.place_time')->find();
        $startdate = '';
        $enddate = date('Y-m-d',time()-86400);
        if ($list) {
            $startdate = date('Y-m-d',$list['place_time']).'-';
        }
        $status = [
            0 => '待结算',
            1 => '已结算',
        ];
        $this->view->assign("statusList", $status);
        $this->view->assign("ids", $row['id']);
        $this->view->assign("shop_name", $middleman['real_name']);
        $this->view->assign("date", $startdate.$enddate);
        return $this->view->fetch();
    }

    public function item1()
    {
        $ids = input('ids',0);
        if (!$ids) $this->error('缺少参数');
        $middleman = Db::name('middleman')->where(['user_id'=>$ids])->find();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $shop_no = input('ids','');// 店铺编号
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $shop_nos = Db::name('shop')->where(['middleman_id'=>$middleman['id']])->field('shop_no')->select();
            if (!$shop_nos) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $shop_no = '';
            foreach ($shop_nos as $key => $value) {
                $shop_no .= $value['shop_no'].',';
            }
            $shop_no = trim($shop_no,',');
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = '1=1';
            if (isset($decode['id']) && $decode['id']) {
                $where2 .= ' and a.id = "'.$decode['id'].'"';
            }
            if (isset($decode['place_time']) && $decode['place_time']) {
                $date = explode(' - ', $decode['place_time']);
                $where2 .= ' and a.place_time >"'.strtotime($date[0]).'" and a.place_time<"'.strtotime($date[1]).'"';
            }
            if (isset($decode['is_pay'])) {
                $where2 .= ' and a.is_pay ='.$decode['is_pay'];
            }
            $sql2 = 'select count(*) as count from (select o.* from chbc_play_order o left join chbc_user_money_log uml on o.play_order_no=uml.tran_no where o.order_status in (3,6,-9) and uml.user_id='.$ids.' and uml.log_type=12 union select o.* from chbc_play_order o left join chbc_shop s on s.shop_no=o.shop_no where o.shop_no in ('.$shop_no.') and o.order_status in (3,6,-9) and o.is_pay=0) a where '.$where2;
            $total = Db::query($sql2);
            $sql = 'select a.* from (select o.* from chbc_play_order o left join chbc_user_money_log uml on o.play_order_no=uml.tran_no where o.order_status in (3,6,-9) and uml.user_id='.$ids.' and uml.log_type=12 union select o.* from chbc_play_order o left join chbc_shop s on s.shop_no=o.shop_no where o.shop_no in ('.$shop_no.') and o.order_status in (3,6,-9) and o.is_pay=0) a where '.$where2.' order by a.id desc limit '.$offset.','.$limit;
            $list = Db::query($sql);
            foreach ($list as $k => &$v) {
                $Play2 = new \app\admin\model\Play2();
                $OrderProof2 = new \app\common\model\OrderProof2();
                $play = $Play2->where('play_no',$v['play_no'])->field('*')->find();
                $proof = $OrderProof2->where('play_order_no',$v['play_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,actual_pay')->find();
                if ($v['cps_id']>0) {
                    $v['one_image'] = '';
                } else {
                    $v['one_image'] = config('oss_domain').$proof['one_image'];
                }
                $v['two_image'] = config('oss_domain').$proof['two_image'];
                $v['three_image'] = config('oss_domain').$proof['three_image'];
                $v['wm_order_sn'] = $proof['wm_order_sn'];
                $v['actual_pay'] = $proof['actual_pay'];
                $v['back_money_text2'] = $play['back_money_text2'];
                $v['scheme_no_text'] = $play['scheme_no_text'];
                $v['rebate_amt'] = $v['actual_rebate_amt']+$v['service_charge_amt'];
                $v['user_id'] = Db::name('user')->where('id',$v['user_id'])->value('nickname');
                $shop = Db::name('shop')->where('shop_no',$v['shop_no'])->find();
                $v['shop_no'] = $shop['shop_name'];
                $v['platform_no'] = config('platform')[$shop['shop_type']];
            }

            $result = array("total" => $total[0]['count'], "rows" => $list);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $row = $this->model->get($ids); // 活动
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $model = new \app\common\model\Order();
        $list = $model->alias('order')->where('order.shop_no="'.$row['shop_no'].'" and order.order_status=3')->order('order.id asc')->field('order.place_time')->find();
        $startdate = '';
        $enddate = date('Y-m-d',time()-86400);
        if ($list) {
            $startdate = date('Y-m-d',$list['place_time']).'-';
        }
        $status = [
            0 => '待结算',
            1 => '已结算',
        ];
        $this->view->assign("statusList", $status);
        $this->view->assign("ids", $row['id']);
        $this->view->assign("shop_name", $middleman['real_name']);
        $this->view->assign("date", $startdate.$enddate);
        return $this->view->fetch();
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        
        // 状态参数过滤掉
        if (isset($filter['anickname'])) {
            unset($filter['anickname']);
        }
        if (isset($filter['nickname'])) {
            unset($filter['nickname']);
        }
        if (isset($filter['mobile'])) {
            unset($filter['mobile']);
        }
        if (isset($filter['no'])) {
            unset($filter['no']);
        }
        if (isset($filter['money'])) {
            unset($filter['money']);
        }
        if (isset($filter['freeze_money'])) {
            unset($filter['freeze_money']);
        }
        if (isset($filter['real_name'])) {
            unset($filter['real_name']);
        }
        if (isset($filter['card_no'])) {
            unset($filter['card_no']);
        }
        if (isset($filter['bank_name'])) {
            unset($filter['bank_name']);
        }
        if (isset($filter['rebate_amt'])) {
            unset($filter['rebate_amt']);
        }
        if (isset($filter['status'])) {
            unset($filter['status']);
        }
        if (isset($filter['logintime'])) {
            unset($filter['logintime']);
        }
        if (isset($filter['ledger_no'])) {
            unset($filter['ledger_no']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }


    public function selectpage()
    {
        $pageNumber = input('pageNumber',1);
        $pageSize = input('pageSize',10);
        $q_word = input('q_word/a');
        $keyField = input('keyField');
        // $keyValue = input('keyValue');
        $where = 'no>0 and real_name<>"" and delete_dt is null';
        $keyword = '';
        if (isset($q_word) && isset($q_word[0])) {
            $keyword = $q_word[0];
            if (!$keyword) {
                $keyword = '';
            }else{
                $where .= ' and real_name like "%'.$keyword.'%"';
            }
        }
        if (isset($_POST['keyValue']) && $_POST['keyValue']==0) {
            return json(['list' => [], 'total' => 0]);
        }
        if ($keyField && isset($_POST['keyValue']) && $_POST['keyValue']>0) {
            $where .= ' and id='.$_POST['keyValue'];
        }
        $list = Db::name('middleman')->where($where)->field('id,real_name')->page($pageNumber,$pageSize)->select();
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => Db::name('middleman')->where($where)->count()]);
    }

    /**
     * 编辑
     */
    public function transferlog($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $ids = input('ids','');// 店铺编号
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (!$ids) {
                $result = array("total" => 0, "rows" => []);

                return json($result);
            }
            $model = new \app\common\model\Order2();
            $list = $model
                ->field('*')
                ->where($where)
                ->where('is_yunzhan=2 and is_pay=1')
                ->order('id DESC')
                ->paginate($limit);
            $data = [];
            foreach ($list as $k => $v) {
                $like = ','.$v['id'].',';
                $bill_log = Db::name('bill_log')->where('play_ids like "%'.$like.'%"')->find();
                $submit_by = Db::name('admin')->where(['id'=>$bill_log['submit_by']])->value('nickname');
                $data[$k]['id'] = $v['id'];
                $data[$k]['start_date_text'] = date('Y-m-d',$v['expire_time']);
                $data[$k]['yunzhan_order_no'] = $v['yunzhan_order_no'];
                // $play_order = (float)Db::name('play_order')->where(['play_no'=>$v['play_no'],'order_status'=>3,'is_pay'=>1])->value('sum(service_charge_amt)+sum(actual_rebate_amt)');
                $data[$k]['sum'] = $v['rebate_amt'];
                $data[$k]['update_dt'] = strtotime($bill_log['update_dt']);
                $data[$k]['submit_by'] = $submit_by?$submit_by:'';
                $data[$k]['img'] = config('upload_domain').$bill_log['img'];
            }

            $result = array("total" => $list->total(), "rows" => $data);

            return json($result);
        }
        $ids = input('ids',0);// 活动id
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }

    /**
     * 线下转账
     * @DateTime 2023-05-02T13:31:14+0800
     * @param    [type]                   $ids [description]
     * @return   [type]                        [description]
     */
    public function transfer($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $play_id = $this->request->post("btSelectItem/a");
            if (!$play_id) $this->error('请选择活动');
            $play_ids = implode(',', $play_id);
            if (Db::name('play_order')->where(['id'=>['in',$play_id],'is_pay'=>1])->field('id')->find()) {
                $this->error('活动数据有误');
            }
            $time = time();
            if ($params) {
                Db::startTrans();
                // try {
                    Db::name('play_order')->where(['id'=>['in',$play_id],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->update(['is_pay'=>1,'pay_time'=>$time]);
                    Db::name('bill_log')->insert([
                        'shop_no' => $params['shop_no'],
                        'type' => '线下转账',
                        'img' => $params['img'],
                        'submit_by' => $this->auth->id,
                        'play_ids' => ','.$play_ids.','
                    ]);
                    Db::commit();
                // } catch (Exception $e) {
                //     Db::rollback();
                //     $this->error('处理失败');
                // }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $OrderModel = new \app\common\model\Order2();
        $ids = input('ids',0);// 活动id
        // $row = $this->model->get($ids); // 活动
        $play_order = Db::name('play_order')->field('is_yunzhan,rebate_amt,service_charge_amt,crood_type,play_no,actual_rebate_amt,id,place_time,is_pay,order_status,yunzhan_order_no,id,wm_order_sn')->where('order_status in (3,6,-9) and is_pay=0 and is_yunzhan=2')->order('id DESC')->select();
        $sum = 0;
        foreach ($play_order as $key => &$value) {
            // $play = [];
            // list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($value['play_no'],$value['crood_type']);
            $value['place_time'] = date('Y-m-d H:i:s',$value['place_time']);
            $value['order_status_text'] = $OrderModel->getOrderStatusTextAttr($value['order_status'],[]);
            $value['is_pay_text'] = $OrderModel->getIsPayTextAttr($value['is_pay'],['is_pay'=>$value['is_pay']]);
            $value['rebate_amt'] = round($value['actual_rebate_amt']+$value['service_charge_amt'],2);
            $sum += $value['rebate_amt'];
        }
        // $this->view->assign("row", $row);
        $this->view->assign("play", $play_order);
        $this->view->assign("ids", $ids);
        $this->view->assign("sum", round($sum,2));
        return $this->view->fetch();
    }


    public function order()
    {
        $OrderModel = new \app\common\model\Order2();
        $date = input('date','');
        $arr = explode(' - ', $date);
        if (count($arr)!=2) {
            $this->error('日期格式有误');
        }
        $play_order = Db::name('play_order')->field('is_yunzhan,rebate_amt,service_charge_amt,crood_type,play_no,actual_rebate_amt,id,place_time,is_pay,order_status,yunzhan_order_no,id,wm_order_sn')->where('order_status in (3,6,-9) and is_pay=0 and is_yunzhan=2')->where('place_time>"'.strtotime($arr[0]).'" and place_time<"'.strtotime($arr[1]).'"')->order('id DESC')->select();
        $sum = 0;
        foreach ($play_order as $key => &$value) {
            // $play = [];
            // list($play,$shop) = (new \app\api\service\PlayService())->mtofficial($value['play_no'],$value['crood_type']);
            $value['place_time'] = date('Y-m-d H:i:s',$value['place_time']);
            $value['order_status_text'] = $OrderModel->getOrderStatusTextAttr($value['order_status'],[]);
            $value['is_pay_text'] = $OrderModel->getIsPayTextAttr($value['is_pay'],['is_pay'=>$value['is_pay']]);
            $value['rebate_amt'] = round($value['actual_rebate_amt']+$value['service_charge_amt'],2);
            $sum += $value['rebate_amt'];
        }
        $this->success('succ',null,['play_order'=>$play_order,'sum'=>round($sum,2)]);
    }

}
